package cn.assumejson.springframework.core.io;

import cn.assumejson.springframework.util.ResourceUtils;
import cn.assumejson.springframework.util.StringUtils;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ObjectUtil;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 读取ClassPath下
 *
 * @author Mr. Li
 * @version 1.0
 * @since 1.0 2021/11/30 12:22
 */
public class ClassPathResource implements Resource {
    private final String path;

    private ClassLoader classLoader;

    public ClassPathResource(String path) {
        this(path, null);
    }

    public ClassPathResource(String path, ClassLoader classLoader) {
        Assert.notNull(path, "Path must not be null");
        String pathToUse = StringUtils.cleanPath(path);
        if (pathToUse.startsWith("/")) {
            pathToUse = pathToUse.substring(1);
        }
        this.path = pathToUse;
        this.classLoader = classLoader == null ? ClassUtil.getClassLoader() : classLoader;
    }

    @Override
    public InputStream getInputStream() throws IOException {
//        InputStream ias = classLoader.getResourceAsStream(path);
        cn.hutool.core.io.resource.ClassPathResource resource = new cn.hutool.core.io.resource.ClassPathResource(path.substring(path.indexOf(ResourceUtils.CLASSPATH_URL_PREFIX)));
        InputStream is = resource.getStream();
        if (ObjectUtil.isNotNull(is)) return is;
        throw new FileNotFoundException(
                this.path + " cannot be opened because it does not exist");
    }
}
